const { Users } = require("./apiModels/user");
// const { APIError } = require("../rest");

module.exports = {
  // 查询用户列表
  "GET /api/user/query": async (ctx, next) => {
    let query = ctx.query;
    let { rows, count } = await Users.queryList(query);
    ctx.rest({
      Users: rows,
      total: count,
    });
  },

  // 注册
  "POST /api/register": async (ctx, next) => {
    let reqBody = ctx.request.body;
    let p = await Users.register(reqBody);
    ctx.rest(p, { message: "用户注册成功" });
  },

  // 登陆
  "POST /api/login": async (ctx, next) => {
    let reqBody = ctx.request.body;
    let p = await Users.login(reqBody);
    ctx.rest(p, { message: "登陆成功" });
  },

  // 获取用户信息
  "GET /api/getUserInfo": async (ctx, next) => {
    const parts = ctx.header.authorization.split(" ");
    if (parts.length === 2) {
      const scheme = parts[0];
      const token = parts[1];

      if (/^Bearer$/i.test(scheme)) {
        let p = await Users.getUserInfo(token);
        ctx.rest(p);
      }
    }
  },

  "GET /api/user/delete/:id": async (ctx, next) => {
    let p = await Users.delete(ctx.params.id);
    ctx.rest(p, { message: "用户删除成功" });
  },

  "POST /api/user/update": async (ctx, next) => {
    let reqBody = ctx.request.body;
    let p = await Users.update(reqBody);
    ctx.rest(p, { message: "密码修改成功" });
  },
};
